package com.example.homework09.service;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.homework09.R;

public class BindSerivce extends Fragment {
    public BindSerivce(){
        super(R.layout.bindservice);
    }
    private MyConn myConn;

    public class MyConn implements ServiceConnection {
        public MusicService2.MyBinder myBinder = null;
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder = (MusicService2.MyBinder)service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Intent intent = new Intent(getActivity(), MusicService2.class);
        getActivity().startService(intent);

        //bindservice
        if (myConn == null) {
            myConn = new MyConn();
            intent = new Intent(getActivity(), MusicService2.class);
            getActivity().bindService(intent, myConn, 0);
        }


        //播放
        getView().findViewById(R.id.btn_play).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(myConn.myBinder == null)
                            return;
                        myConn.myBinder.play();
                    }
                }
        );

        //下一首
        getView().findViewById(R.id.btn_next).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(myConn.myBinder == null)
                            return;
                        myConn.myBinder.next();
                    }
                }
        );

        //暂停
        getView().findViewById(R.id.btn_pause).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(myConn.myBinder == null)
                            return;
                        myConn.myBinder.pause();
                    }
                }
        );
    }
}
